import json
import math

from flask import render_template, jsonify, request, session

from blues.cluster.cluster_base import get_cluster_dict
from blues.cluster.cluster_deploy import update_image
from blues.job import bp
from blues.job.job_dingtalk import job_create_msg, job_succeed_msg
from blues.job.job_jenkins import create_jenkins_job, create_gitlab_file
from config import JOB_STATE, JOB_TYPE
from model.area import Area
from model.auditor import Auditor
from model.cluster import Cluster
from model.jenkins_kube_info import JenkinsKubeInfo
from model.job import Job


@bp.route('/job')
def home():
    j = Job()
    # result = j.find_limit(0, 10)
    result = j.find_all()
    total = math.ceil(j.get_total_count() / 10)
    return render_template('job.html', result=result, total=total, page=1, active='job')


# @job_blue.route('/job/page/<int:page>')
# def paginate(page):
#     start = (page - 1) * 10
#     j = Job()
#     result = j.find_limit(start, 10)
#     total = math.ceil(j.get_total_count() / 10)
#     return render_template('job.html', result=result, total=total, page=page, active='job')


@bp.route('/job/type')
def select_type():
    return render_template('job-type.html', active='job')


@bp.route('/job/type-1/add')
def job_1_add():
    c = Cluster()
    cluster_list = c.find_all()
    a = Auditor()
    auditor_list = a.find_all()
    return render_template('job-type-1-add.html', clusters=cluster_list, auditors=auditor_list, active='job')


@bp.route('/api/v1/job/all', methods=['GET'])
def api_all():
    CLUSTER_DICT = get_cluster_dict()
    j = Job()
    # try:
    list = j.find_all()
    for i in list:
        params = json.loads(i['params'])
        i['cluster'] = ''
        if i['type'] == 1:
            i['cluster'] = CLUSTER_DICT[int(params[0]['cluster_id'])]
        i["state"] = JOB_STATE[i["state"]]
        i["type"] = JOB_TYPE[i["type"]]
        i["create_time"] = i["create_time"].strftime("%Y-%m-%d %H:%M:%S")
        if i["audit_time"]:
            i["audit_time"] = i["audit_time"].strftime("%Y-%m-%d %H:%M:%S")
    return jsonify({"code": 200, "data": list})
    # except Exception as e:
    #     print(e)
    #     return jsonify({"code": 500, "message": str(e),  "data": []})


@bp.route('/api/job/<job_id>/approve', methods=['GET'])
def api_approve(job_id):
    CLUSTER_DICT = get_cluster_dict()
    silence = request.args.get('silence')

    j = Job()
    job = j.find_by_id(job_id)

    services = json.loads(job['params'])
    auditor = session.get('username')

    content_dict = {}
    for svc in services:
        print(content_dict)
        print(svc['cluster_id'], svc['namespace'], svc['microservice'], svc['image'])
        update_image(svc['cluster_id'], svc['namespace'], svc['microservice'], svc['image'])
        if svc['cluster_id'] not in content_dict.keys():
            content_dict[svc['cluster_id']] = []
        content_dict[svc['cluster_id']].append("{} => {}".format(svc['microservice'], svc['image'].split(":")[1]))
    j.approve_update(job_id, auditor, 2, '')

    print("silence?" + silence)
    if silence != "true":
        content = "[对勾]服务发布完成，请验收\n工单ID：" + job_id + "\n审批人：" + auditor + "\n"
        for k, v in content_dict.items():
            content += "\n集群：{}".format(CLUSTER_DICT[int(k)])
            i = 1
            for s in v:
                content += "\n{}. {}".format(i, s)
                i += 1
        content += "\n"
        job_succeed_msg(content)
    return 'success'


@bp.route('/api/job/<job_id>/deny', methods=['POST'])
def api_deny(job_id):
    data = request.json

    j = Job()
    job = j.find_by_id(job_id)

    services = json.loads(job['params'])
    auditor = session.get('username')

    content_dict = {}
    for svc in services:
        if svc['cluster_id'] not in content_dict.keys():
            content_dict[svc['cluster_id']] = []
        content_dict[svc['cluster_id']].append("{} => {}".format(svc['microservice'], svc['image'].split(":")[1]))
    j.approve_update(job_id, auditor, 3, data['deny_reason'])

    content = "[打叉]服务发布被拒绝\n工单ID：" + job_id + "\n审批人：" + auditor + "\n拒绝理由：" + data['deny_reason'] + "\n"
    cdict = get_cluster_dict()
    for k, v in content_dict.items():
        content += "\n集群：{}".format(cdict[int(k)])
        i = 1
        for s in v:
            content += "\n{}. {}".format(i, s)
            i += 1
    content += "\n"
    job_succeed_msg(content)
    return 'success'


@bp.route('/job/<job_id>')
def job_detail(job_id):
    j = Job()
    job = j.find_by_id(job_id)
    cdict = get_cluster_dict()
    services = json.loads(job['params'])
    return render_template('job-type-1-detail.html', job=job, cdict=cdict, services=services, active='job')


@bp.route('/api/v1/job/type-1/add', methods=['POST'])
def job_add_api():
    data = request.json
    print(data)
    content_dict = {}
    for svc in data['svcArray']:
        print(svc['cluster_id'], svc['namespace'], svc['microservice'], svc['image'])
        if svc['cluster_id'] not in content_dict.keys():
            content_dict[svc['cluster_id']] = []
        content_dict[svc['cluster_id']].append("{} => {}".format(svc['microservice'], svc['image'].split(":")[1]))

    try:
        job = Job()
        job_id = job.insert(type=data['type'], comment=data['comment'], params=json.dumps(data['svcArray']))
    except Exception as e:
        print(e)
        return 'error'

    # 钉钉消息末尾添加@审批人
    a = Auditor()
    auditor = a.find_by_id(data['auditor_id'])
    content = ''
    if auditor:
        content += "@" + auditor['phone']

    content += "服务发布申请\n工单ID：" + job_id + "\n申请人：" + session.get('username') + "\n更新说明：" + data['comment'] + "\n"
    cdict = get_cluster_dict()
    for k, v in content_dict.items():
        content += "\n集群：{}".format(cdict[int(k)])
        i = 1
        for s in v:
            content += "\n{}. {}".format(i, s)
            i += 1
    content += "\n"
    job_create_msg(content, auditor['phone'])

    return 'success'


################ job type 2 ################


@bp.route('/job/type-2/add')
def job_add_cicd_page():
    return render_template('job-type-2-add.html', active='job')


@bp.route('/api/v1/job/type-2/add', methods=['POST'])
def job_add_cicd_api():
    b = request.json
    print(b)
    create_jenkins_job(
        b['job_name'],
        b['job_desc'],
        b['code_repo'],
        b['conf_repo'],
    )
    create_gitlab_file(
        b['kube_id'],
        b['cluster_ns'],
        b['app_name'],
        b['node_port'],
        b['code_repo'],
        b['conf_repo'],
        b['image'],
        b['pre_cd'],
        b['build_tool'],
        b['tier'],
        b['include_arm64'],
    )
    # 存入mysql
    try:
        job = Job()
        job.insert(type=2, comment='新建服务：' + b['app_name'], state=2, params=json.dumps(b))
    except Exception as e:
        print(e)

    return 'success'


@bp.route('/api/v1/area_list')
def areaList():
    a = Area()
    try:
        area_list = a.find_all()
        return jsonify({"code": 200, "data": area_list})
    except Exception as e:
        print(e)
        return jsonify({"code": 500, "message": str(e)})


@bp.route('/api/v1/kube_info_list')
def kubeInfoList():
    area_id = request.args.get('area_id')
    try:
        k = JenkinsKubeInfo()
        Kube_info_list = k.find_by_area(area_id)
        return jsonify({"code": 200, "data": Kube_info_list})
    except Exception as e:
        print(e)
        return jsonify({"code": 500, "message": str(e)})
